<template>
  <div id="login-main">
    <div class="container">
      <div class="top">
        <img src="~@/assets/logo.svg" class="logo" alt="logo">
        <span class="title">{{title}}</span>
      </div>
      <a-form
        id="formLogin"
        class="user-layout-login"
        ref="formLogin"
      >
        <a-tabs
          :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        >
          <a-tab-pane key="tab1" tab="账户密码登录">
            <a-alert
              v-if="isLoginError"
              type="error"
              showIcon
              style="margin-bottom: 24px;"
              message="账户或密码错误"
            />
            <a-form-item v-bind="validateInfos.userName">
              <a-input
                size="large"
                type="text"
                placeholder="请输入帐户名或邮箱地址"
                v-model:value="formRef.userName"
              />
            </a-form-item>

            <a-form-item v-bind="validateInfos.password">
              <a-input-password
                size="large"
                placeholder="请输入密码"
                v-model:value="formRef.password"
              >
              </a-input-password>
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
        <a-form-item style="margin-top:24px">
          <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="login-button"
            @click.prevent="handleSubmit"
          >登录</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  toRefs,
  reactive,
  onMounted,
} from 'vue';
import {
  Form,
  Tabs,
  Input,
  Button,
  Alert,
} from 'ant-design-vue';
import { useRoute, useRouter, LocationQuery } from 'vue-router';
import { useStore } from 'vuex';
import { UserActionTypes } from '@/store/modules/user/types';

const { title } = require('@/config/vue.custom.config');

const enum LOGIN_TYPE {
  EMAIL,
  USERNAME,
}

export default defineComponent({
  components: {
    AForm: Form,
    ATabs: Tabs,
    ATabPane: Tabs.TabPane,
    AFormItem: Form.Item,
    AInput: Input,
    AInputPassword: Input.Password,
    AButton: Button,
    AAlert: Alert,
  },
  setup() {
    const { useForm } = Form;
    const route = useRoute();
    const router = useRouter();
    const store = useStore();
    const state = reactive({
      isLoginError: false,
      loginType: 0,
      formLogin: null,
      title,
      redirect: '',
      otherQuery: {},
      formRef: {
        userName: '',
        password: '',
      },
    });

    function handleUsernameOrEmail(_: any, value: string) {
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
      state.loginType = regex.test(value) ? LOGIN_TYPE.EMAIL : LOGIN_TYPE.USERNAME;
      return Promise.resolve();
    }

    const rulRef = reactive({
      userName: [
        { required: true, message: '请输入帐户名或邮箱地址', trigger: 'change' },
        { validator: handleUsernameOrEmail, trigger: 'change' },
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
      ],
    });

    const { validate, validateInfos } = useForm(state.formRef, rulRef);

    function handleSubmit() {
      validate()
        .then(async () => {
          await store.dispatch(UserActionTypes.ACTION_LOGIN, state.formRef);
          state.isLoginError = false;
          router.push({
            path: state.redirect || '/',
            query: state.otherQuery,
          }).catch((err) => {
            console.warn(err);
          });
        })
        .catch(() => {
          state.isLoginError = true;
        });
    }

    function getOtherQuery(query: LocationQuery) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur];
        }
        return acc;
      }, {} as LocationQuery);
    }

    onMounted(() => {
      const { query } = route;
      if (query) {
        state.redirect = query.redirect?.toString() ?? '';
        state.otherQuery = getOtherQuery(query);
      }
    });

    return {
      ...toRefs(state),
      validateInfos,
      handleSubmit,
    };
  },
});
</script>
<style lang="less" scoped>
#login-main {
  height: 100vh;
  background: #f0f2f5 url(~@/assets/background.svg) no-repeat 50%;
  background-size: 100%;
  padding: 32px 0 24px;
  .container {
    min-width: 260px;
    width: 368px;
    margin: 0 auto;
  }
  .top {
    text-align: center;
  }
  .logo {
    height: 44px;
    vertical-align: middle;
    margin-right: 16px;
    border-style: none;
  }
  .title {
    font-size: 33px;
    color: rgba(0, 0, 0, .85);
    font-weight: 600;
    vertical-align: middle;
  }
  .user-layout-login {
    label {
      font-size: 14px;
    }
    .forge-password {
      font-size: 14px;
    }

    button.login-button {
      padding: 0 15px;
      font-size: 16px;
      height: 40px;
      width: 100%;
    }
  }
}
</style>
